﻿var express = require('express'),
    router = express.Router()
var async = require('async')
var moment = require('moment')
var ObjectID = require('mongodb').ObjectID;
var multiparty = require('multiparty');
var fs = require('fs')
var mkdirp = require('mkdirp');
var im = require('imagemagick');
var easyimage = require('easyimage')
var sha = require('js-sha1')
var phoneVerification = require('../util/phoneVerification.js')
const schedule = require('node-schedule');
const child_process = require('child_process');

var md5 = require('md5')
    // var Brand = require('../model/brand.js')

const AdminUser = require('../model/adminUser.js')
var node_cache = require('node-cache')
const AdminCache = new node_cache({ stdTTL: 100 * 24 * 3600, checkperiod: 120 });

const UserInfo = require('../model/userinfo.js')
const Follower = require('../model/follower.js')
const CommentUser = require('../model/commentuser.js')
const Count = require('../model/count.js')
const MyAccount = require('../model/myaccount.js')
const SearchAccount = require('../model/searchaccount.js')
const OtherAccount = require('../model/otheraccount.js')
const Discourse = require('../model/discourse.js')
const UidUser = require('../model/uiduser.js')
const Repostuser = require('../model/repostuser.js')
const InteractiveUser = require('../model/interactiveUser.js')
const NeedDeleteUid = require('../model/needDeleteUid.js')
process.env.TZ = 'Asia/Shanghai'

const path = 'd:/'


let env = process.env.NODE_WEIBO
let mode = 0
if (env == 'test') {
    mode = 1
}
console.log(env, 'env')
router.get('/test', function(req, res) {
    UserInfo.findOne().exec(function(err, data) {
        console.log(data)
        console.log(data.addTime)
        console.log(data.shortID, data.account, data.addTime, data.uid)
        console.log(new Date())
        console.log(new Date(data.addTime))
        res.send(data)
    })
})



router.post('/exportMyUsers', function(req, res) {

    var query = {}

    if ((req.body.keyword != undefined) && (req.body.keyword != '')) {
        // query.accountName = req.body.keyword
        query.accountName = req.body.keyword
    }
    if (req.body.gender != -1) {
        query.gender = req.body.gender
    }
    query.source = 0
    query.own = 1
    query.exclude = 0
    UserInfo.find(query).sort({ addTime: -1 }).exec(function(err, data) {

        var xlsx = require('node-xlsx').default
        var datab = []
        datab.push(['关注账号', '昵称', 'uid', '性别', '所在地', '抓取时间', '类别'])
        for (var i = 0; i < data.length; i++) {
            let sex = '未知'
            if (data[i].gender == 0) {
                sex = '男'
            } else if (data[i].gender == 1) {
                sex = '女'
            }
            datab.push([data[i].accountName, data[i].nickname, data[i].uid, sex, data[i].city, formatDate(new Date(data[i].updatetime)), '自己人'])
        }
        datab.sort(function(a, b) { a.province != null })
        var buffer = xlsx.build([{ name: "mySheetName", data: datab }]);
        res.send({ code: 200, data: buffer.toString('base64') })

        // var datab = ''
        // for (var i = 0; i < data.length; i++) {
        //     datab += data[i].uid
        //     datab += '\n'
        // }
        // res.send({ code: 200, data: datab })


    })

})


router.post('/expotRepostUser', function(req, res) {

    Repostuser.find({ postID: req.body.postID }).exec(function(err, data) {
        var xlsx = require('node-xlsx').default
        var datab = []
        datab.push(['关注账号', '昵称', 'uid', '性别', '所在地', '抓取时间'], '类别')
        for (var i = 0; i < data.length; i++) {
            let sex = '未知'
            if (data[i].gender == 0) {
                sex = '男'
            } else if (data[i].gender == 1) {
                sex = '女'
            }
            datab.push([data[i].accountName, data[i].nickname, data[i].uid, sex, formatDate(new Date(data[i].addTime)), data[i].category])
        }
        datab.sort(function(a, b) { a.province != null })
        var buffer = xlsx.build([{ name: "mySheetName", data: datab }]);
        res.send({ code: 200, data: buffer.toString('base64') })

        // var datab = ''
        // for (var i = 0; i < data.length; i++) {
        //     datab += data[i].uid
        //     datab += '\n'
        // }
        // res.send({ code: 200, data: datab })
    })
})

router.post('/exportChatUsers', function(req, res) {

    var query = {}

    if ((req.body.keyword != undefined) && (req.body.keyword != '')) {
        // query.accountName = req.body.keyword
        query.account = req.body.keyword
    }
    if (req.body.gender != -1) {
        query.gender = req.body.gender
    }
    query.source = 1
    query.own = 1
    query.exclude = 0
    UserInfo.find(query).sort({ addTime: -1 }).exec(function(err, data) {
        var xlsx = require('node-xlsx').default
        var datab = []
        datab.push(['关注账号', '昵称', 'uid', '性别', '所在地', '抓取时间', '类别'])
        for (var i = 0; i < data.length; i++) {
            let sex = '未知'
            if (data[i].gender == 0) {
                sex = '男'
            } else if (data[i].gender == 1) {
                sex = '女'
            }
            datab.push([data[i].accountName, data[i].nickname, data[i].uid, sex, data[i].city, formatDate(new Date(data[i].updatetime)), '自己人'])
        }
        datab.sort(function(a, b) { a.province != null })
        var buffer = xlsx.build([{ name: "mySheetName", data: datab }]);
        res.send({ code: 200, data: buffer.toString('base64') })
            // var datab = ''
            // for (var i = 0; i < data.length; i++) {
            //     datab += data[i].uid
            //     datab += '\n'
            // }
            // res.send({ code: 200, data: datab })


    })

})


router.post('/exportOtherUsers', function(req, res) {

    var query = {}

    if ((req.body.keyword != undefined) && (req.body.keyword != '')) {
        query.account = req.body.keyword
            // query.accountName = req.body.keyword
    }
    if (req.body.gender != -1) {
        query.gender = req.body.gender
    }
    if (req.body.source != undefined) {
        query.source = req.body.source
    }
    let sort = {}
    if (query.source == 2) {
        sort = { 'account': 1, 'interactiontime': -1 }
    } else if (query.source == 0) {
        sort = { 'account': 1, 'addTime': -1 }
    }
    query.exclude = 0
    sort['account'] = 1
    if (req.body.month) {
        let newDate = new Date()
        newDate = new Date(newDate.setMonth(newDate.getMonth() - req.body.month))
        if (query.source == 2) {
            query.interactiontime = { $gte: newDate }
        }
        if (query.source == 0) {
            query.addTime = { $gte: newDate }

        }
    }
    query.own = { $ne: 1 }
    UserInfo.find(query).sort(sort).exec(function(err, data) {
        // console.log(data,'???')
        var xlsx = require('node-xlsx').default
        var datab = []
        datab.push(['关注账号', '昵称', 'uid', '性别', '所在地', query.source == 0 ? '抓取时间' : '最近互动时间', '类别'])
        for (var i = 0; i < data.length; i++) {
            let sex = '未知'
            if (data[i].gender == 0) {
                sex = '男'
            } else if (data[i].gender == 1) {
                sex = '女'
            }

            datab.push([data[i].accountName, data[i].nickname, data[i].uid, sex, data[i].city, formatDate(new Date(query.source == 0 ? data[i].addTime : data[i].interactiontime)), data[i].category])
                // console.log(data[i].interactiontime,'aahhaha')
        }
        datab.sort(function(a, b) { a.province != null })
        var buffer = xlsx.build([{ name: "mySheetName", data: datab }]);
        res.send({ code: 200, data: buffer.toString('base64') })
            // var datab = ''
            // for (var i = 0; i < data.length; i++) {
            //     datab += data[i].uid
            //     datab += '\n'
            // }
            // res.send({ code: 200, data: datab })


    })

})




router.post('/exportFollowerUsers', function(req, res) {

    var query = {}

    if ((req.body.keyword != undefined) && (req.body.keyword != '')) {
        query.account = req.body.keyword
    }
    if (req.body.gender != undefined) {
        if (req.body.gender != 1) {
            query.gender = req.body.gender
        }
    }
    query.exclude = 0

    Follower.find(query).sort({ addTime: -1 }).exec(function(err, data) {
        var xlsx = require('node-xlsx').default
        var datab = []
        datab.push(['抖音粉丝', '昵称', '性别', '省份', '城市', 'uid', 'shortID', 'uniqueID', '抓取时间'])
        for (var i = 0; i < data.length; i++) {
            datab.push([data[i].account, data[i].nickname, data[i].gender, data[i].province, data[i].city, data[i].uid, data[i].shortID, data[i].uniqueID, new Date(data[i].addTime)])
        }
        var buffer = xlsx.build([{ name: "mySheetName", data: datab }]);
        res.send({ code: 200, data: buffer.toString('base64') })
            // var datab = ''
            // for (var i = 0; i < data.length; i++) {
            //     datab += data[i].uid
            //     datab += '\n'
            // }
            // res.send({ code: 200, data: datab })


    })

})


router.post('/exportCommentUsers', function(req, res) {

    var query = {}

    if ((req.body.keyword != undefined) && (req.body.keyword != '')) {
        query.videoOwner = req.body.keyword
    }
    if (req.body.gender != undefined) {
        if (req.body.gender != 1) {
            query.gender = req.body.gender
        }
    }
    if ((req.body.startTime != undefined) && (req.body.startTime != '')) {
        if ((req.body.endTime != undefined) && (req.body.endTime != '')) {
            query.commentTime = { $gte: new Date(req.body.startTime), $lte: new Date(req.body.endTime) }
        } else {
            query.commentTime = { $gte: new Date(req.body.startTime) }
        }
    } else {
        if ((req.body.endTime != undefined) && (req.body.endTime != '')) {
            query.commentTime = { $lte: new Date(req.body.endTime) }
        }
    }




    CommentUser.find(query).exec(function(err, data) {
        var xlsx = require('node-xlsx').default
        var datab = []
        datab.push(['视频大号', '昵称', '性别', '评论时间', '评论', 'uid', 'shortID', 'uniqueID'])
        for (var i = 0; i < data.length; i++) {
            let sex = '未知'
            if (data[i].gender == 1.0) {
                sex = '男'
            } else if (data[i].gender == 2.0) {
                sex = '女'
            }
            datab.push([data[i].videoOwner, data[i].nickname, sex, data[i].commentTime, data[i].comment, data[i].uid, data[i].short, data[i].uniqueID])
        }
        var buffer = xlsx.build([{ name: "mySheetName", data: datab }]);
        console.log('hey hey', data.length)
        res.send({ code: 200, data: buffer.toString('base64') })
            // var datab = ''
            // for (var i = 0; i < data.length; i++) {
            //     datab += data[i].uid
            //     datab += '\n'
            // }
            // res.send({ code: 200, data: datab })
    })

})



router.post('/allUsers', async(req, res) => {
    if (req.body.keyword == '统计') {
        count('today')
    } else if (req.body.keyword == '昨天') {
        count('yesterday')
    } else if (req.body.keyword == "更新") {
        statistical()
    } else {
        if (userValidation(req.session.id, req.body.session, res)) {
            var query = {}
            var xlsx = require('node-xlsx').default
            var datab = []
            if ((req.body.keyword != undefined) && (req.body.keyword != '')) {
                query.account = req.body.keyword
            }
            if (req.body.gender != undefined) {
                if (req.body.gender != 1) {
                    query.gender = req.body.gender
                }
            }
            let userInfoes = await UserInfo.find(query).sort({ searched: -1 }).exec()
            datab.push(['本列表中出现次数', 'UID', '昵称', '抖音号', '性别', '年龄', '地域省', '地域市', '地域区', 'TV集团否', '行为时间', '来源分类', '来源账号', '来源账号UID', '新增粉', '新增粉日期', '在某账号评论数＞20', '评论次数'])
                // console.log(userInfoes[0])
            for (let i = 0; i < userInfoes.length; i++) {
                datab.push([userInfoes[i].counts, userInfoes[i].uid, userInfoes[i].nickname, userInfoes[i].shortID, userInfoes[i].gender, '', userInfoes[i].province, userInfoes[i].city, '', userInfoes[i].isTVG == 1 ? '是' : '否', new Date(userInfoes[i].updatetime), '', userInfoes[i].fromAccount, '', userInfoes[i].newUser == 0 ? '否' : '是', new Date(userInfoes[i].addTime || userInfoes[i].updatetime), userInfoes[i].moreThanTimes == 0 ? '否' : '是', userInfoes[i].commentTimes])
            }
            // console.log(userInfoes)
            var buffer = xlsx.build([{ name: "mySheetName", data: datab }]);
            res.send({ code: 200, data: buffer.toString('base64') })
                // var datab = ''
                // for (var i = 0; i < data.length; i++) {
                //     datab += data[i].uid
                //     datab += '\n'
                // }
            res.send({ code: 200, data: datab })


        }
    }
})



// login return status & session id
router.post('/admin_login', function(req, res) {
    //console.log(req.session,req.session.id)
    var userid = req.body.account
    var password = req.body.password
    AdminUser.findOne({ userid: userid, password: sha(password) }, function(err, data) {
        if (data == null) {
            // var newadminuser = new AdminUser()
            // newadminuser.userid = userid
            // newadminuser.password = sha(password)
            // newadminuser.loggedIn = [new Date()]
            // newadminuser.lastTimeLoggedIn = new Date()
            // newadminuser.level = 0
            // newadminuser.save(function(err){
            // 	res.send({'code' : 200,'session':'123'})
            // })
            res.send({ 'code': 400 })
        } else {
            data.loggedIn.push(new Date())
            data.lastTimeLoggedIn = new Date()
            data.save(function(err) {
                AdminCache.set(req.sessionID, { userid: userid, rights: data.rights }, function(err, success) {

                    res.send({ 'code': 200, 'session': req.session.id, rights: data.rights })
                })
            })
        }
    })
})


router.post('/getUserList', function(req, res) {
    console.log('calling')
    const spawn = require("child_process").spawn;
    // console.log(spawn)
    let file = fs.existsSync('python/getUserListInfo.py')
    console.log(file)
    let var1 = 'ab'
    let var2 = 'bc'
    const pythonProcess = spawn('python', ["python/getUserListInfo.py", var1, var2, mode]);
    // console.log(pythonProcess,'ds')
    pythonProcess.stdout.on('data', (data) => {
        console.log(data.toString(), 'dssds')
            // Do something with the data returned from python script
    })
})


router.get('/getMyAccount', function(req, res) {
    MyAccount.find({}, function(err, data) {
        res.send({ 'code': 200, data: data })

    })
})


router.post('/saveMyAccount', function(req, res) {
    var schemes = JSON.parse(req.body.methods)
    async.each(schemes, function(key, callback) {
        console.log(key._id)
        if (key._id == undefined) {
            var newMyAccount = new MyAccount()
            newMyAccount.name = key.name
            newMyAccount.uid = key.uid

            newMyAccount.save(callback)
        } else {
            MyAccount.findOne({ _id: ObjectID.createFromHexString(key._id) }, function(err, data) {
                data.name = key.name
                data.uid = key.uid
                data.save(callback)
            })
        }
    }, function(err) {
        res.send({ 'code': 200 })
    })
})

router.post('/removeMyAccount', function(req, res) {

    MyAccount.findOneAndRemove({ _id: req.body.id }).exec(function(err) {
        res.send({ 'code': 200 })
    })
})



router.get('/getSearchAccount', function(req, res) {
    SearchAccount.find({}, function(err, data) {
        res.send({ 'code': 200, data: data })
    })
})


router.post('/saveSearchAccount', function(req, res) {
    console.log('ok')
    var schemes = JSON.parse(req.body.methods)
    async.each(schemes, function(key, callback) {
        if (key._id == undefined) {
            var newSearchAccount = new SearchAccount()
            newSearchAccount.name = key.name
            newSearchAccount.uid = key.uid

            newSearchAccount.save(callback)
        } else {
            SearchAccount.findOne({ _id: ObjectID.createFromHexString(key._id) }, function(err, data) {
                data.name = key.name
                data.uid = key.uid
                data.save(callback)
            })
        }
    }, function(err) {
        res.send({ 'code': 200 })
    })
})

router.post('/removeSearchAccount', function(req, res) {

    SearchAccount.findOneAndRemove({ _id: req.body.id }).exec(function(err) {
        res.send({ 'code': 200 })
    })
})


router.post('/searchlogin', function(req, res) {
    let name = req.body.name
    let uid = req.body.uid
    const spawn = require("child_process").spawn;
    // console.log(spawn)
    let file = fs.existsSync('python/firstLogin.py')
        // console.log(file)
    let var1 = name
    let var2 = uid
    console.log('hahahah,lll', file)
    const pythonProcess = spawn('python', ["python/firstLogin.py", var1, var2, mode]);
    // console.log(pythonProcess,'ds')
    console.log(var1, var2, 'var1')
    pythonProcess.stdout.on('data', (data) => {
        console.log(data.toString(), 'dssds')
            // Do something with the data returned from python script
    })
    console.log('ok')
    res.send({ 'code': 200 })
})


router.get('/getOtherAccount', function(req, res) {
    OtherAccount.find({}, function(err, data) {
        res.send({ 'code': 200, data: data })

    })
})


router.post('/saveOtherAccount', function(req, res) {
    var schemes = JSON.parse(req.body.methods)
    async.each(schemes, function(key, callback) {
        console.log(key._id)
        if (key._id == undefined) {
            var newOtherAccount = new OtherAccount()
            newOtherAccount.name = key.name
            newOtherAccount.uid = key.uid

            newOtherAccount.save(callback)
        } else {
            OtherAccount.findOne({ _id: ObjectID.createFromHexString(key._id) }, function(err, data) {
                data.name = key.name
                data.uid = key.uid
                data.save(callback)
            })
        }
    }, function(err) {
        res.send({ 'code': 200 })
    })
})

router.post('/removeOtherAccount', function(req, res) {

    OtherAccount.findOneAndRemove({ _id: req.body.id }).exec(function(err) {
        res.send({ 'code': 200 })
    })
})


router.post('/firstlogin', function(req, res) {
    let name = req.body.name
    let uid = req.body.uid
    const spawn = require("child_process").spawn;
    // console.log(spawn)
    let file = fs.existsSync('python/firstlogin.py')
    console.log(file, 'dsd')
        // console.log(file)
    let var1 = name
    let var2 = uid
    const pythonProcess = spawn('python', ["python/firstlogin.py", var1, var2, mode]);
    pythonProcess.stdout.on('data', (data) => {
        console.log('jb')
        console.log(data.toString(), 'dssds')
            // Do something with the data returned from python script
    })
    console.log('ok')
    res.send({ 'code': 200 })
})

router.post('/uploadUID', function(req, res) {
    let data = req.body.data

    async.forEach(data, function(key, callback) {
        if (key != undefined) {

            UidUser.findOne({ uid: key, account: req.body.account }).exec(function(err, data) {
                if (data == null) {
                    let newUID = new UidUser()
                    newUID.addTime = new Date()
                    newUID.uid = key
                    newUID.account = req.body.account
                    newUID.save(function(e) {
                        callback()
                    })
                } else {
                    callback()
                }
            })
        } else {
            callback()
        }
    }, function(e) {
        res.send({ code: 200 })
    })
})

router.post('/uploadneeddeleteuid',function(req,res){
    let data = req.body.data
    async.forEach(data, function(key, callback) {
        if (key != undefined) {
            console.log(key)
            NeedDeleteUid.findOne({ uid: key.uid, account: key.account }).exec(function(err, data) {
                if (data == null) {
                    let newUID = new NeedDeleteUid()
                    newUID.addTime = new Date()
                    newUID.uid = key.uid
                    newUID.account = key.account
                    newUID.deleted = 0
                    newUID.updatetime = new Date()
                    newUID.save(function(e) {
                        callback()
                    })
                } else {
                    callback()
                }
            })
        } else {
            callback()
        }
    }, function(e) {
        res.send({ code: 200 })
    })
})

router.post('/postFanList', function(req, res) {
    const spawn = require("child_process").spawn;

    let uid = req.body.repostUID
    let repostID = req.body.repostID
    console.log(uid, repostID)
    SearchAccount.find({}).exec(function(err, dataa) {
        if (dataa == undefined) {
            res.send({ 'code': 201 })
            return
        }
        const pythonProcess = spawn('python', ["python/assignWeiboReposter.py", uid, repostID, dataa[0].name, dataa[0].uid, mode]);
        pythonProcess.stdout.on('data', (data) => {
            console.log(data.toString(), 'dssds')
                // Do something with the data returned from python script
        })
        res.send({ 'code': 200 })
    })
})

router.post('/deleteMyAccountFans', function(req, res) {
    const spawn = require("child_process").spawn;
    // console.log(req.body.uid,'sds')
    MyAccount.findOne({ uid: req.body.uid }).exec(function(err, data) {
        if (data == null) {
            res.send({ 'code': 201 })
            return false
        }
        let uid = req.body.uid
        let condition = req.body.condition
        let deleteMode = req.body.deleteMode
            // console.log(uid,data.name,condition,deleteMode,mode,'mmm')
        const pythonProcess = spawn('python', ["python/deleteMyAccountFans.py", uid, data.name, condition, deleteMode, mode]);
        pythonProcess.stdout.on('data', (data) => {
            console.log(data.toString(), 'dssds')
                // Do something with the data returned from python script
        })
        res.send({ 'code': 200 })
    })

})


router.post('/deleteCommenUser', function(req, res) {

    const spawn = require("child_process").spawn;

    let uid = req.body.repostID
    let repostID = req.body.repostUID
    console.log(uid, repostID)
        // SearchAccount.find({}).exec(function(err, dataa) {
        //     if (dataa == undefined){
        //         res.send({'code':201})
        //         return
        //     }
    uid = 1160032062
    MyAccount.findOne({ uid: uid }).exec(function(err, data) {

        if (data == null) {
            res.send({ 'code': 201 })
            return
        } else {
            console.log('calling', data)
            uid = 5850745184
            console.log(uid, data.name, repostID, mode, 'srever')
            const pythonProcess = spawn('python', ["python/commentUserDelete.py", uid, data.name, repostID, mode]);
            pythonProcess.stdout.on('data', (data) => {
                console.log(data.toString(), 'dssds')
                    // Do something with the data returned from python script
            })
            res.send({ 'code': 200 })

        }

    })



})


router.post('/runMyAccountFans', function(req, res) {
    MyAccount.find({}).exec(function(err, data) {
        async.each(data, function(key, callback) {
            const spawn = require("child_process").spawn;
            // console.log(spawn)
            let file = fs.existsSync('python/getUserListInfo.py')
            let var1 = key.name
            let var2 = key.uid
            let fanMode = req.body.fanMode
            let repostID = req.body.repostID
            const pythonProcess = spawn('python', ["python/getUserListInfo.py", var1, var2, fanMode, repostID, mode]);
            // console.log(pythonProcess,'ds')
            // console.log("python/getUserListInfo.py", var1, var2, fanMode, repostID, mode)
            pythonProcess.stdout.on('data', (data) => {
                console.log(data.toString(), 'dssds')
                    // Do something with the data returned from python script
            })
        })
        res.send({ 'code': 200 })
    })
})

router.post('/repostFans', function(req, res) {
    MyAccount.find({}).exec(function(err, data) {
        async.each(data, function(key, callback) {
            const spawn = require("child_process").spawn;
            // console.log(spawn)
            let mode = 0 // 0不发私信 1发私信
            let file = fs.existsSync('python/repostFans.py')
            let var1 = key.name
            let var2 = key.uid
            let repostID = req.body.repostID
            const pythonProcess = spawn('python', ["python/repostFans.py", var1, var2, repostID, mode]);
            console.log("python/repostFans.py", var1, var2, repostID, mode)
            pythonProcess.stdout.on('data', (data) => {
                console.log(data.toString(), 'dssds')
                    // Do something with the data returned from python script
            })
        })
        res.send({ 'code': 200 })
    })
})

router.get('/runOtherAccountFans', function(req, res) {
    SearchAccount.find({}).exec(function(err, dataa) {
        OtherAccount.find({}).exec(async function(err, data) {
            const spawn = require("child_process").spawn;
            // console.log(spawn)
            let file = fs.existsSync('python/getOtherUserList.py')
            console.log(file)

            // for (var i = 0; i < dataa.length ; i++){
            let var1 = data[0].name
            let var2 = data[0].uid
            let var3 = dataa[0].name
            // const pythonProcess = spawn('python', ["python/getOtherUserList.py", var1, var2, var3, mode]);
            let parameter = var1 + ' ' +var2+' ' + var3 +' '+mode
            // console.log("python/getOtherUserList.py", var1, var2, var3, mode)
            const pythonProcess = spawn('python', ["python/mainProc.py","python/getOtherUserList.py", parameter]);
            // console.log(pythonProcess,'ds')
            // console.log("python/getOtherUserList.py", var1, var2, var3, mode)
            pythonProcess.stdout.on('data', (data) => {
                    console.log(data.toString(), 'dssds')
                        // Do something with the data returned from python script
                })
                // }


            // async.each(data,function(key,callback){
            // 	const spawn = require("child_process").spawn;
            // 	// console.log(spawn)
            // 	let file = fs.existsSync('python/getOtherUserList.py')
            // 	console.log(file)
            // 	let var1 = key.name
            // 	let var2 = key.uid
            // 	let var3 = dataa[0].name
            // 	const pythonProcess = spawn('python', ["python/getOtherUserList.py", var1, var2,var3]);
            // 	// console.log(pythonProcess,'ds')
            // 	pythonProcess.stdout.on('data', (data) => {
            // 		console.log(data.toString(), 'dssds')
            // 		// Do something with the data returned from python script
            // 	})
            // })
            res.send({ 'code': 200 })
        })
    })
})



router.post('/deleteCommenUser', function(req, res) {

    const spawn = require("child_process").spawn;

    let uid = req.body.repostID
    let repostID = req.body.repostUID
    console.log(uid, repostID)
        // SearchAccount.find({}).exec(function(err, dataa) {
        //     if (dataa == undefined){
        //         res.send({'code':201})
        //         return
        //     }
    uid = 1160032062
    MyAccount.findOne({ uid: uid }).exec(function(err, data) {

        if (data == null) {
            res.send({ 'code': 201 })
            return
        } else {
            console.log('calling', data)
            uid = 5850745184
            console.log(uid, data.name, repostID, mode, 'srever')
            const pythonProcess = spawn('python', ["python/commentUserDelete.py", uid, data.name, repostID, mode]);
            pythonProcess.stdout.on('data', (data) => {
                console.log(data.toString(), 'dssds')
                    // Do something with the data returned from python script
            })
            res.send({ 'code': 200 })

        }

    })



})




router.get('/runChatFansList', function(req, res) {
    MyAccount.find({}).exec(function(err, data) {
        async.each(data, function(key, callback) {
            const spawn = require("child_process").spawn;
            // console.log(spawn)
            let file = fs.existsSync('python/chatList.py')
            let var1 = key.name
            let var2 = key.uid
            const pythonProcess = spawn('python', ["python/chatList.py", var1, var2, mode]);
            // console.log(pythonProcess,'ds')
            pythonProcess.stdout.on('data', (data) => {
                console.log(data.toString(), 'dssds')
                    // Do something with the data returned from python script
            })
        })
        res.send({ 'code': 200 })
    })
})



router.get('/runotherInteractiveFansList', async(req, res, next) => {
    let dataa = await SearchAccount.find({}).exec()
    let data = await OtherAccount.find({}).exec()
    const spawn = require("child_process").spawn;
    // console.log(spawn)
    let file = fs.existsSync('python/getOtherAccountUserInfo.py')
    console.log(file)
    for (var i = 0; i < dataa.length; i++) {
        // console.log('bbb')

        let var1 = data[0].name
        let var2 = data[0].uid
        let lenx = dataa.length
        let index = i
        let var3 = dataa[index].name
        const pythonProcess = await spawn('python', ["python/getOtherAccountUserInfo.py", var1, var2, var3, mode]);
        // console.log(pythonProcess,'ds')
        pythonProcess.stdout.on('data', (data) => {
            console.log(data.toString(), 'dssds' + i)
                // Do something with the data returned from python script
        })
    }
    res.send({ 'code': 200 })

    // 	SearchAccount.find({}).exec(function(err,dataa){
    // 		OtherAccount.find({}).exec(function(err,data){
    // 		// async.each(data,function(key,callback){
    // 			const spawn = require("child_process").spawn;
    // 			// console.log(spawn)
    // 			let file = fs.existsSync('python/getOtherAccountUserInfo.py')
    // 			console.log(file)
    // 			// for (var i = 0 ;i < dataa.length ; i++){
    // 				console.log('bbb')

    // 			let var1 = data[0].name
    // 			let var2 = data[0].uid
    // 			let lenx = dataa.length
    // 			let index = 0
    // 			let var3 = dataa[index].name
    // 			const pythonProcess = spawn('python', ["python/getOtherAccountUserInfo.py", var1, var2,var3,mode]);
    // 			// console.log(pythonProcess,'ds')
    // 			pythonProcess.stdout.on('data', (data) => {
    // 				console.log(data.toString(), 'dssds' + i)
    // 				// Do something with the data returned from python script
    // 			})
    // 		// }
    // 		// })
    // 		res.send({'code':200})
    // 	})
    // })
})

            // router.get('/updateUserInfo', function(req, res) {
            //     SearchAccount.find({}).exec(function(err, data) {
            //         // async.each(data,function(key,callback){
            //         const spawn = require("child_process").spawn;
            //         // console.log(spawn)
            //         let file = fs.existsSync('python/needUpdateUser.py')
            //         let index = Math.floor(Math.random() * data.length)
            //         let var1 = data[index].name
            //         const pythonProcess = spawn('python', ["python/needUpdateUser.py", var1, mode]);
            //         // console.log(pythonProcess,'ds')
            //         console.log("python/needUpdateUser.py", var1, mode)
            //         pythonProcess.stdout.on('data', (data) => {
            //                 console.log(data.toString(), 'dssds')
            //                     // Do something with the data returned from python script
            //             })
                        // })
router.post('/saveDiscourse', function(req, res) {
    Discourse.findOne({}).exec(function(err, data) {
        if (data != null) {
            data.description = req.body.description,
                data.send = req.body.send,
                data.save(function(err, datax) {
                    res.send({ 'code': 200 })
                })
        } else {
            newDescription = new Discourse()
            newDescription.description = req.body.description,
                newDescription.send = req.body.send,
                newDescription.save(function(err, datax) {
                    res.send({ 'code': 200 })
                })
        }
    })
})


router.post('/getDiscourse', function(req, res) {
    console.log('run')
    Discourse.findOne({}).exec(function(err, data) {
        console.log(data)
        res.send({ 'code': 200, data: data })
    })
})

router.post('/getMyAccount', function(req, res) {
    console.log('run')
    MyAccount.find({}).exec(function(err, data) {
        res.send({ 'code': 200, data: data })
    })
})


router.post('/deleteUid', function(req, res) {
    MyAccount.find({_id:req.body.accountID}).exec(function(err, data) {
        console.log(req.body.accountID,data)
        const spawn = require("child_process").spawn;
        // console.log(spawn)
        let file = fs.existsSync('python/deleteUserByUid.py')
        // let index = Math.floor(Math.random() * data.length)
        let var1 = data[0].name
        let var2 = data[0].uid
        const pythonProcess = spawn('python', ["python/deleteUserByUid.py", var1,var2, mode]);
        // console.log(pythonProcess,'ds')
        pythonProcess.stdout.on('data', (data) => {
                console.log(data.toString(), 'dssds')
                    // Do something with the data returned from python script
            })
        res.send({ 'code': 200 })
    })
})



router.get('/updateUserInfo', function(req, res) {
    SearchAccount.find({}).exec(function(err, data) {
        // async.each(data,function(key,callback){
        const spawn = require("child_process").spawn;
        // console.log(spawn)
        let file = fs.existsSync('python/needUpdateUser.py')
        let index = Math.floor(Math.random() * data.length)
        let var1 = data[index].name
        const pythonProcess = spawn('python', ["python/needUpdateUser.py", var1, mode]);
        // console.log(pythonProcess,'ds')
        pythonProcess.stdout.on('data', (data) => {
                console.log(data.toString(), 'dssds')
                    // Do something with the data returned from python script
            })
            // })
        res.send({ 'code': 200 })
    })
})

function count(day) {
    if (day == 'yesterday') {
        var startDate = new Date(new Date(new Date().toLocaleDateString()).getTime() - 24 * 60 * 60 * 1000)
        var endDate = new Date(new Date(new Date().toLocaleDateString()).getTime() - 1)
    } else if (day = 'today') {
        var startDate = new Date(new Date().toLocaleDateString())
        var endDate = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
    }
    let newcount = new Count()
    UserInfo.countDocuments({ $and: [{ updatetime: { $gte: startDate } }, { updatetime: { $lte: endDate } }] }, function(err, data) {
        UserInfo.countDocuments({ $and: [{ updatetime: { $gte: startDate } }, { updatetime: { $lte: endDate } }, { searched: 1 }] }, function(err, dataa) {
            CommentUser.countDocuments({ $and: [{ updatetime: { $gte: startDate } }, { updatetime: { $lte: endDate } }] }, function(err, datab) {
                console.log('列表：' + data, '详情：' + dataa, '评论：' + datab)
                newcount.userList = data
                newcount.userInfo = dataa
                newcount.comment = datab
                newcount.createDate = new Date()
                newcount.save()
            })
        })
    })
}

async function statistical() {
    console.log('开始')
        // var datab = []
    let counts = []
    let now = new Date()
    let tvAcoount = ['TangVisionGirl', 'tang vision 婚纱摄影']
    let newUserDays = 7 * 86400000

    let userInfoes = await UserInfo.find().exec()
    let carryOut = 0
        // datab.push(['本列表中出现次数', 'UID', '昵称', '抖音号', '性别', '年龄', '地域省', '地域市', '地域区', 'TV集团否', '行为时间', '来源分类', '来源账号', '来源账号UID', '新增粉', '新增粉日期', '在某账号评论数＞20', '评论次数'])
    for (var i = 0; i < userInfoes.length; i++) {
        // console.log(userInfoes[i])
        let sex = '未知'
        if (userInfoes[i].gender == 1.0) {
            sex = '男'
        } else if (userInfoes[i].gender == 2.0) {
            sex = '女'
        }
        let countBy = userInfoes[i].uid || userInfoes[i].nickname
        if (counts[countBy] == undefined) {
            counts[countBy] = 1
        } else {
            counts[countBy] = counts[countBy] + 1
        }
        let isTVG = (await UserInfo.find({ uid: userInfoes[i].uid, account: { $in: tvAcoount } }).exec()).length == 0 ? false : true
        let date = userInfoes[i].addTime || userInfoes[i].updatetime
        let newUser = (now - date - newUserDays) >= 0 ? false : true
        let comments = await CommentUser.find({ $or: [{ nickname: userInfoes[i].nickname }, { uid: userInfoes[i].uid }] }).exec()
        let commentCounts = []
        let moreThanTimes = false
        for (let j = 0; j < comments.length; j++) {
            // let commentCountBy = userInfoes[i].uid ||userInfoes[i].nickname
            let commentCountBy = userInfoes[i].videoOwner
            if (commentCounts[commentCountBy] == undefined) {
                commentCounts[commentCountBy] = 1
            } else {
                commentCounts[commentCountBy] = commentCounts[commentCountBy] + 1
                if (commentCounts[commentCountBy] >= 20) {
                    moreThanTimes = true
                }
            }
        }
        UserInfo.findById(userInfoes[i]._id).exec(function(err, user) {
            user.statisticalDate = new Date(),
                user.counts = counts[countBy],
                user.isTVG = isTVG,
                // user.fromType = String,
                user.newUser = newUser ? 1 : 0,
                user.moreThanTimes = moreThanTimes ? 1 : 0,
                user.commentTimes = comments.length
            user.save()
            console.log(userInfoes.length, carryOut)
            carryOut = carryOut + 1
        })

        // datab.push([counts[countBy], userInfoes[i].uid, userInfoes[i].nickname, userInfoes[i].shortID,sex, '', userInfoes[i].province, userInfoes[i].city, '', isTVG ? '是': '否', new Date(userInfoes[i].updatetime), '', userInfoes[i].account, '', newUser ? '是':'否', new Date(userInfoes[i].addTime || userInfoes[i].updatetime) , moreThanTimes ? '是':'否',comments.length ])
        // console.log('出现次数：'+counts[countBy]+'；是否集团：'+isTVG+'；行为时间'+userInfoes[i].updatetime+'；新增时间'+userInfoes[i].addTime+'；来源账号'+userInfoes[i].account+'；新粉丝否'+newUser+'；新粉丝日期'+userInfoes[i].addTime || userInfoes[i].updatetime+'；评论数'+commentCounts)
    }
    console.log('完成')
        // var buffer = xlsx.build([{ name: "mySheetName", data: datab }]);
        // res.send({code:200,data:buffer.toString('base64')})
}




function userValidation(sessionSelf, session, res) {
    console.log(sessionSelf, session)
    if (sessionSelf != session) {
        return true
            //res.send({'code':401})
            //return false
    } else {
        return true
    }
}

function saveOneImage(filename, file, path, callback) {
    // console.log(path + filename,'??')
    mkdirp(path, function(err) {

        //
        // fs.writeFile(filename, file, 'base64',function (err) {
        // 	callback(err)
        // })
        var path1 = path + filename
        var path2 = path + 't_' + filename
        fs.writeFile(path1, file, 'base64', function(err) {
            easyimage.resize({
                src: path1,
                dst: path1,
                width: 800

            }).then(function(err, stdout, stderr) {
                // console.log(err,'err')
                easyimage.resize({
                    src: path1,
                    dst: path2,
                    width: 250,
                    height: 250

                }).then(function(err, stdout, stderr) {
                    // console.log(err,'sss')
                    callback(err)
                })
            })
        })

    })
}


function formatDate(date) {
    var xdate = new Date(date)
    var year = xdate.getFullYear()
    var day = xdate.getDate()
    var month = xdate.getMonth()
    var hour = xdate.getHours()
    var minute = xdate.getMinutes()
    return String(year) + '-' + String(month + 1) + '-' + String(day) + ' ' + String(addZeroBefore(hour)) + ':' + String(addZeroBefore(minute))
}

function formatDay(date) {
    var xdate = new Date(date)
    var year = xdate.getFullYear()
    var day = xdate.getDate()
    var month = xdate.getMonth()
    var hour = xdate.getHours()
    var minute = xdate.getMinutes()
    return String(year) + '-' + String(month + 1) + '-' + String(day)
}

function addZeroBefore(n) {
    return (n < 10 ? '0' : '') + n;
}

function exportTxt() {
    var date = formatDay(new Date)
        // console.log(date)
    console.log('scheduleCronstyle:' + new Date());
    var startDate = new Date(new Date().toLocaleDateString())
        // var startDate = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000)
    var endDate = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
        // let userinfo = await UserInfo.find({}).exec()
    UserInfo.find({ $and: [{ addTime: { $gte: startDate } }, { addTime: { $lte: endDate } }, { followerCount: { $gte: 20 } }, { postCount: { $gte: 20 } }, { fansCount: { $gte: 20 } }] }, function(err, data) {
        // console.log(data,'data')
        var temp = []
            // if(data){
        for (let i = 0; i < data.length; i++) {
            var check = temp.map(function(e) { return e.category })
            var index = check.indexOf(data[i].category)

            if (index == -1) {
                var arr = {}
                arr.category = data[i].category;
                // arr.uid = new Array()
                // arr.uid.push(data[i].uid);
                arr.uid = data[i].uid
                temp.push(arr);
            } else {
                // temp[index].uid.push(data[i].uid)
                temp[index].uid = temp[index].uid + "\r\n" + data[i].uid
            }
            if (i == data.length - 1) {
                for (let j = 0; j < temp.length; j++) {
                    fs.writeFile(date + temp[j].category + ".txt", temp[j].uid, (err, data) => {
                        if (err) {
                            console.log(err)
                        };
                    });
                }
            }
        }
        // }else{

        // }
    })
}



async function assignexport() {
    let interactiveUser = await InteractiveUser.find({}).exec()
    var xlsx = require('node-xlsx').default
    var datab = []
    datab.push(['微博账号', '该条微博ID','昵称', '性别', 'uid'])
    for (var i = 0; i < interactiveUser.length; i++) {
        console.log('runtestassign')
        let sex = '未知'
        if (interactiveUser[i].gender == 1) {
            sex = '男'
        } else if (interactiveUser[i].gender == 2) {
            sex = '女'
        }
        datab.push([interactiveUser[i].accountName, interactiveUser[i].weiboID,interactiveUser[i].nickname, sex, interactiveUser[i].uid])
    }
    var buffer = xlsx.build([{ name: "mySheetName", data: datab }]);
    await fs.writeFile( './export/'+interactiveUser[0].accountName+'微博互动.xlsx',buffer,function(err,data){
        console.log(err||data)
    })
    
}

const scheduleCronstyle = () => {
    schedule.scheduleJob('0 50 23 * * *', () => {
        exportTxt()
    });
}


// const exportassign = () => {
//     schedule.scheduleJob('0 30 10 * * *', () => {
//         assignexport()
//     });
// }

// assignexport()


// scheduleCronstyle();

module.exports = router